<template>
  <div class="app-container">
    <!--分类维护-->
    <div style="display: flex; align-items: center; gap: 10px;">
      <el-switch
        style="display: block"
        v-model="draggable"
        active-color="#13ce66"
        inactive-color="#ff4949"
        active-text="开启拖拽">
      </el-switch>
      <el-button v-if="draggable" @click="handleBatchSave" type="success">保存</el-button>
      <el-button type="danger" @click="handleBatchDelete">删除</el-button>
    </div>
    <el-tree
      show-checkbox
      :draggable="draggable"
      :allow-drop="allowDrop"
      :allow-drag="allowDrag"
      node-key="catId"
      :data="childrenList"
      :props="defaultProps"
      :expand-on-click-node="false"
      :default-expanded-keys="expandedKey"
      @node-drop="handleDrop"
      ref="tree">
    <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level<=2"
            type="text"
            size="mini"
            @click="() => handleAdd(data)">
            新增
          </el-button>
           <el-button
             type="text"
             size="mini"
             @click="() => handleUpdate(data)">
            修改
          </el-button>
          <el-button
            v-if="node.childNodes.length===0"
            type="text"
            size="mini"
            @click="() => handleDelete(node, data)">
            删除
          </el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form :model="form" ref="form" label-width="100px" class="demo-ruleForm">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>

        <el-form-item label="显示状态" prop="showStatus">
          <el-radio-group v-model="form.showStatus">
            <el-radio
              v-for="dict in dict.type.category_show_status"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort"></el-input>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="form.icon"></el-input>
        </el-form-item>
        <el-form-item label="计量单位" prop="productUnit">
          <el-input v-model="form.productUnit"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" prop="productCount">
          <el-input v-model="form.productCount"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm()">确定</el-button>
          <el-button @click="cancel()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {add, children, edit, getInfo, remove, removes, updatePmsCategoryList} from "@/api/product/category";

export default {
  name: "category",
  dicts: ['category_show_status'],
  data() {
    return {
      //开启拖拽
      draggable: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 参数表格数据
      childrenList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      //默认展示的节点
      expandedKey: [],
      //被修改的分类集合
      updateCatrgoryList: [],
      //节点最大深度
      maxLevel: 0,
      // 表单参数
      form: {},
      defaultProps: {
        children: 'childrens', //子节点数组
        label: 'name' //展示的字段
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询商品三级分类列表(树形结构) */
    getList() {
      this.loading = true
      children().then(response => {
          this.childrenList = response.rows
          this.total = response.total
          this.loading = false
        }
      )
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        name: null,
        parentCid: null,
        catLevel: null,
        showStatus: null,
        icon: null,
        productUnit: null,
        productCount: null,
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd(data) {
      this.reset()
      this.form.parentCid = data.catId
      //防止字符串
      this.form.catLevel = parseInt(data.catLevel) + 1
      this.open = true
      this.title = "添加分类"
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.configId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const catId = row.catId
      getInfo(catId).then(response => {
        this.form = response.data
        this.form.showStatus = this.form.showStatus.toString()
        this.open = true
        this.title = "修改分类"

      })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.catId != undefined) {
            edit(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            add(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
          this.expandedKey = [this.form.parentCid]
        }
      })
      this.getList()
    },
    /** 删除按钮操作 */
    handleDelete(node, data) {
      const catIds = [data.catId]
      this.$modal.confirm('是否确认删除名称为"' + data.name + '"的分类项？').then(function () {
        return remove(catIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
        this.expandedKey = [data.parentCid]
      }).catch(() => {
      })
    },
    //共四个参数，依次为：被拖拽节点对应的 Node、结束拖拽时最后进入的节点、被拖拽节点的放置位置（before、after、inner）、event
    //拖拽成功完成时修改排序、层级、父节点
    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log(draggingNode, dropNode, dropType)
      let newCatLevel = 0;
      let newParentCid = 0;
      let nodes = null;
      if (dropType === 'before' || dropType === 'after') {
        newCatLevel = dropNode.data.catLevel
        newParentCid = dropNode.data.parentCid
        nodes = dropNode.parent.data.childrens
        console.log(nodes, newCatLevel, 45646)
      } else {
        newCatLevel = dropNode.data.catLevel + 1
        newParentCid = dropNode.data.catId
        nodes = dropNode.data.childrens
      }
      for (let i = 0; i < nodes.length; i++) {
        console.log(nodes[i].catLevel, 789798)
        nodes[i].catLevel = newCatLevel;
        nodes[i].parentCid = newParentCid;
        this.updateChildNodesCatLevel(nodes[i])
        nodes[i].sort = i + 1;
        this.updateCatrgoryList.push(nodes[i])
      }
    },
    //判断节点能否被拖拽
    allowDrop(draggingNode, dropNode, type) {
      //计算当前节点的最大深度
      this.countNodeLevel(draggingNode)
      let deep = Math.abs(this.maxLevel - draggingNode.data.catLevel) + 1
      if (type === 'inner') {
        return (deep + dropNode.level) <= 3
      }
      return (deep + dropNode.parent.level) <= 3
    },
    allowDrag(draggingNode) {
      return true
    },
    //计算当前节点的最大深度
    countNodeLevel(node) {
      if (node.childNodes == null || node.childNodes.length === 0) {
        this.maxLevel = node.level
        return
      }
      let children = node.childNodes[0];
      if (children.level > this.maxLevel) {
        this.maxLevel = children.level
        this.countNodeLevel(children)
      }
    },
    updateChildNodesCatLevel(node) {
      if (node.childNodes == null || node.childNodes.length == 0) {
        return
      }
      for (let childNode in node.childNodes) {
        childNode.catLevel = node.catLevel + 1
        this.updateCatrgoryList.push(childNode)
        this.updateChildNodesCatLevel(childNode)
      }
    },
    handleBatchSave() {
      updatePmsCategoryList(this.updateCatrgoryList).then(response => {
        if (response.code === 200) {
          this.$modal.msgSuccess("修改成功")
        } else {
          this.$modal.msgSuccess("修改失败")
        }
      })
    },
    handleBatchDelete(){
      let catIds=[]
      let nodes=this.$refs.tree.getCheckedNodes()
      for (let node of nodes) {
        catIds.push(node.catId)
      }
      this.$modal.confirm('是否确认进行批量删除操作？').then(function () {
        return removes(catIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    }
  }
}
</script>

<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
